# -*- coding: utf-8 -*-
"""
@author: 木头人
@time: 2024/5/15 16:18
"""

import pymysql
from dbutils.pooled_db import PooledDB  # 3.0以后版本
import threading

class SqlHelper(object):

    def __init__(self):
        self.pool = PooledDB(
            creator=pymysql,  # 使用链接数据库的模块
            maxconnections=6,  # 连接池允许的最大连接数，0和None表示不限制连接数
            mincached=2,  # 初始化时，链接池中至少创建的空闲的链接，0表示不创建
            blocking=True,  # 连接池中如果没有可用连接后，是否阻塞等待。True，等待；False，不等待然后报错
            ping=0,
            # ping MySQL服务端，检查是否服务可用。# 如：0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
            # 数据表 bjpowernode   "web05"
            host='127.0.0.1',
            port=3306,
            user='root',
            password='1142lcq',
            database="remotedb",
            charset='utf8'
        )

        self.local=threading.local()

    def QueryStatement(self,sql,*args,**kwargs):
        conn, cursor = self.open()
        ## 打印实际输出的sql语句
        print('打印实际输出的sql语句:', cursor.mogrify(sql, *args, **kwargs))


    def __enter__(self):
        conn,cursor=self.open()
        rv=getattr(self.local,'stack',None)
        if not rv:
            self.local.stack=[(conn,cursor)]
        else:
            rv.append((conn,cursor))
            self.local.stack=rv
        return

    def __exit__(self, exc_type, exc_val, exc_tb):
        rv = getattr(self.local, 'stack', None)
        if not rv:
            return
        conn,cursor=self.local.stack.pop()
        cursor.close()
        conn.close()


    def open(self):
        conn = self.pool.connection()
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        return conn,cursor

    def close(self,cursor,conn):
        cursor.close()
        conn.close()

    def fetchall(self,sql,*args,**kwargs):

        conn,cursor=self.open()
        cursor.execute(sql,*args,**kwargs)
        self.QueryStatement(sql,*args,**kwargs)
        result=cursor.fetchall()
        self.close(cursor,conn)

        return result

    def fetchone(self,sql,*args,**kwargs):
        conn, cursor = self.open()
        cursor.execute(sql, *args, **kwargs)
        self.QueryStatement(sql,*args,**kwargs)
        result = cursor.fetchone()
        self.close(cursor, conn)
        return result


    def insertOneData(self,sql,*args,**kwargs):
        conn, cursor = self.open()
        cursor.execute(sql, *args, **kwargs)
        self.QueryStatement(sql,*args,**kwargs)
        # 提交到数据库执行
        conn.commit()
        self.close(cursor, conn)

    def insertBatchData(self,sql,*args,**kwargs):
        conn, cursor = self.open()
        cursor.executemany(sql, *args, **kwargs)
        self.QueryStatement(sql,*args,**kwargs)
        # 提交到数据库执行
        conn.commit()
        self.close(cursor, conn)

    def explain2sql(self,sql,*args,**kwargs):
        conn, cursor = self.open()
        cursor.execute('EXPLAIN ANALYZE'+sql, *args, **kwargs)
        self.QueryStatement('EXPLAIN ANALYZE'+sql, *args, **kwargs)
        result = cursor.fetchone()
        self.close(cursor, conn)
        return result

    def show2table(self,sql):
        conn, cursor = self.open()
        cursor.execute(sql)
        self.QueryStatement(sql)
        result = cursor.fetchone()
        self.close(cursor, conn)
        return result

    def alter2table2column(self,sql):
        conn, cursor = self.open()
        cursor.execute(sql)
        self.QueryStatement(sql)
        result = cursor.fetchone()
        self.close(cursor, conn)
        return result

dbHelper=SqlHelper()